package com.lemon.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;

/**
 * @create_time 2016年6月14日 上午2:02:52
 * @author lim
 * @description
 *
 */
public class QNFileUpload {
	private static Logger log = LoggerFactory.getLogger(QNFileUpload.class);
	//	public static final String QINIUPATH = "http://phgdd2bvw.bkt.clouddn.com/"; //七牛的图片临时访问域名
	public static final String QINIUPATH = "http://cpimg.chengpao8.cn/"; //七牛的图片访问域名
	// 设置好账号的ACCESS_KEY和SECRET_KEY
	private static String ACCESS_KEY = "Jb4gTyXcbff24vEG4i0-3J2kMG91g_LYszHLhYdx";
	private static String SECRET_KEY = "CjG83KKKbggeG1or_jRviS2renaxKSsm0hoTxMmr";
	// 要上传的空间
	private static String bucketname = "chengpao";
	// 上传文件的路径
	//上传路径
	private static String rootPath = "";

	// 密钥配置
	private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	static Configuration cfg = new Configuration(Zone.zone1());
	// 创建上传对象
	private static UploadManager uploadManager = new UploadManager(cfg);

	// 简单上传，使用默认策略，只需要设置上传的空间名就可以了
	private static String getUpToken() {
		return auth.uploadToken(bucketname);
	}

/*	public static Response upload(String filePath, String remoteName)
			throws IOException {
		Response res =null;
		try {
			// 调用put方法上传
			 res=uploadManager.put(filePath, remoteName, getUpToken());
			// 打印返回的信息
			log.info(res.bodyString());
			return res;
		} catch (QiniuException e) {
			res = e.response;
			// 请求失败时打印的异常的信息
			log.error(res.toString());
			try {
				// 响应的文本信息
				log.error(res.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
			return res;
		}
	}*/
	
	
	public static void main(String[] args) {
		String dd = "D:/4.jpg";
		Map<String , Object> map = getImageInfo(dd);

		System.out.println(map.get("a"));

		String a = map.get("a").toString();
		if (StringUtil.isNotBlank(a)) {
			int aa = Integer.parseInt(a);
			System.out.println(aa / 100000);
			if (aa / 100000 >= 1) {
				try {
					Builder<File> quality = Thumbnails.of(dd).scale(1f).outputQuality(0.5f);

					String string = quality.toString();
					System.out.println(string);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		/*
		 * String upload = upload("D:\\3.jpg" , "123.jpg");
		 * System.out.println(upload);
		 */
	}
	public static String upload(String filePath, String remoteName) {
		String url ="";
		Response res = null;
		try {
			res=uploadManager.put(filePath, remoteName, getUpToken());
			if(res.isOK()){
				url = rootPath + JSON.parseObject(res.bodyString(),QnSuccess.class).getKey();
			}
		} catch (QiniuException e) {
			res = e.response;
			e.printStackTrace();
			log.error(res.toString());// 请求失败时打印的异常的信息
			try {
				log.error(res.bodyString());// 响应的文本信息
			} catch (QiniuException e1) {
	
			}
		}
		
		return url;
		
	}

	public static String upload(InputStream inputStream , String remoteName) {
		String url = "";
		String key = null;
		try {

			Auth auth = Auth.create(ACCESS_KEY , SECRET_KEY);
			String upToken = auth.uploadToken(getUpToken());
			try {
				Response response = uploadManager.put(inputStream , remoteName , getUpToken() , null , null);
				if (response.isOK()) {
					url = rootPath + JSON.parseObject(response.bodyString() , QnSuccess.class).getKey();
					return url;
				}

				//解析上传成功的结果
				DefaultPutRet putRet = new Gson().fromJson(response.bodyString() , DefaultPutRet.class);
				System.out.println(putRet.key);
				System.out.println(putRet.hash);
			} catch (QiniuException ex) {
				Response r = ex.response;
				System.err.println(r.toString());
				try {
					System.err.println(r.bodyString());
				} catch (QiniuException ex2) {
					//ignore
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return url;

	}

	public static Map<String , Object> getImageInfo(String filePath) {

		long startTime = System.currentTimeMillis();
		Map<String , Object> imageInfoMap = new HashMap<>();
		InputStream is = null;
		try {
			File file = new File(filePath);
			is = new FileInputStream(file);
			BufferedImage image = ImageIO.read(is);
			imageInfoMap.put("a" , file.length());
			imageInfoMap.put("b" , image.getWidth());
			imageInfoMap.put("c" , image.getHeight());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close(); // 关闭流
				} catch (IOException e) {
					System.out.println("getImageInfo I/O exception " + e.getMessage());
				}
			}
		}
		long endTime = System.currentTimeMillis();
		System.out.println("take time: " + (endTime - startTime));
		return imageInfoMap;
	}
}

class QnSuccess {

	private String path;
	private String key;
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	
}